package com.eascs.web.o2o.web.controller;

import java.util.Date;

import javax.inject.Inject;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.scheduler.common.entity.ScheduleJob;
import com.eascs.scheduler.common.service.IDubboJobService;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.web.o2o.web.form.ScheduleJobForm;
import com.eascs.web.o2o.web.service.QuartzService;
import com.eascs.web.sso.UserHolder;

@RestController
@RequestMapping("/rest_quartz")
public class QuartzRestController extends BaseRestController {

	Logger logger =LoggerFactory.getLogger(QuartzRestController.class);
	
	@Inject
	QuartzService quartzService;

	@Reference
	IDubboJobService iDubboJobService;

	@RequestMapping(value = "/saveJob")
	public BaseRestResult<String> saveJob(ScheduleJobForm vo) {
		BaseRestResult<String> result = null;
		if (vo.getJobName() == null || vo.getClassPath() == null
				|| vo.getMethod() == null && vo.getCronExpression() == null) {
			result = BaseRestResult.warn("'任务名称'，'所在类'，'执行方'法，'Cron表达式'都不能为空，请确认信息完成！");
		} else {
			if ("add".equals(vo.getFlag())) {
				ScheduleJob s = quartzService.getJobByName(vo.getClassPath(), vo.getMethod());
				if (s != null) {
					result = BaseRestResult.warn("该'执行方法'的任务已经添加，请不要重复添加！");
				}
				ScheduleJob s1 = quartzService.getJobByJobName(vo.getJobName());
				if (s1 != null) {
					result = BaseRestResult.warn("'任务名称'不能重复！");
				}
				ScheduleJob job = quartzService.saveScheduleJob(vo, null);
				boolean flag = quartzService.insertEntity(job);
				if (flag == false) {
					result = BaseRestResult.warn("保存失败！");
				} else {
					result = BaseRestResult.info("添加成功").andRedirect("/quartz/jobList");
				}

			} else if ("update".equals(vo.getFlag())) {
				ScheduleJob job = quartzService.saveScheduleJob(vo, quartzService.getJobById(vo.getJobId()));
				boolean flag = quartzService.updateEntity(job);
				if (flag == false) {
					result = BaseRestResult.warn("修改失败！");
				} else {
					// 更新任务
					if (("1").equals(job.getJobStatus())) {// 任务可执行
						try {
							iDubboJobService.updateScheduleJobByCron(job);
						} catch (Exception e) {
							logger.error("updateScheduleJobByCron：dubbo链接异常！", e);
							result = BaseRestResult.error("updateScheduleJobByCron：dubbo链接异常！");
						}
					}
					result = BaseRestResult.info("添加成功").andRedirect("/quartz/jobList");
				}
			}
		}
		ViewContext.put("vo", vo);
		return result;
	}

	/*
	 * 任务设置：暂停0，运行1
	 */
	@RequestMapping(value = "/useJob")
	public BaseRestResult<String> useJob(ScheduleJobForm vo) {

		ScheduleJob job = quartzService.getJobById(vo.getJobId());
		if (("0").equals(job.getJobStatus())) {//暂停中
			boolean flag = false;
			try {
				 flag = iDubboJobService.isExistJob(job);
			} catch (Exception e) {
				logger.error("任务是否存在isExistJob：dubbo链接异常！", e);
				return BaseRestResult.error("任务是否存在isExistJob：dubbo链接异常！");
			}
			job.setJobStatus("1");
			if(flag){//
				try {
					iDubboJobService.resumeJob(job);
				} catch (Exception e) {
					logger.error("运行resumeJob：dubbo链接异常！", e);
					return BaseRestResult.error("运行resumeJob：dubbo链接异常！");
				}
			}else{
				try {
					iDubboJobService.addScheduleJob(job);
				} catch (Exception e) {
					logger.error("添加任务addScheduleJob：dubbo链接异常！", e);
					return BaseRestResult.error("添加任务addScheduleJob：dubbo链接异常！");
				}
			}
		} else {//运行中
			job.setJobStatus("0");
			try {
				iDubboJobService.pauseJob(job);
			} catch (Exception e) {
				logger.error("暂停pauseJob：dubbo链接异常！", e);
				return BaseRestResult.error("暂停pauseJob：dubbo链接异常！");
			}
		}
		job.setUpdateTime(new Date());
		job.setUpdatePsn(UserHolder.getUser().getCname());
		quartzService.updateEntity(job);
		return BaseRestResult.info("设置成功").andRedirect("/quartz/jobList");
	}

	/*
	 * 任务设置：暂停0，运行1
	 */
	@RequestMapping(value = "/deleteJob")
	public BaseRestResult<String> deleteJob(ScheduleJobForm vo) {
		try {
			ScheduleJob job = quartzService.getJobById(vo.getJobId());
		    try {
		    	iDubboJobService.deleteJob(job);
			} catch (Exception e) {
				logger.error("删除deleteJob：dubbo链接异常！", e);
				return BaseRestResult.error("删除deleteJob：dubbo链接异常！");
			}
			quartzService.deleteEntityById(vo.getJobId());
		} catch (Exception e) {
			return BaseRestResult.info("移除失败").andRedirect("/quartz/jobList");
		}
		return BaseRestResult.info("移除成功").andRedirect("/quartz/jobList");

	}

}
